<?php

namespace Modules\Category\Http\Controllers;

use Illuminate\Support\Facades\Log; // 引入 Log 类
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Category\Models\Category;
use Illuminate\Validation\Rule;
use Modules\Category\Helpers\helpers;
class CategoryController extends Controller
{
public function select(Request $request){
    // 只有传了 status 参数才使用过滤，否则 null 表示不过滤
    $status = $request->has('status') ? (int)$request->query('status') : null;
    $tree = categoryTree($status);
    return response()->json($tree);
}
public function checkInput(Request $request){
        $request->validate(
            ['name'=>'required|max:16|unique:categories,name'],
            ['name.required'=>'分类名称不能为空','name.unique'=>'分类名称已存在']
        );
        $group = $request->input('group', 'goods');
        $pid   = $request->input('pid', 0);
        $level = $pid ? (Category::find($pid)?->level + 1 ?? null) : 1;
        if ($pid && !$level) return cat_error('父级分类不存在');
        if ($level > 3) return cat_error('分类层级不能超过3级');
        return ['pid'=>$pid,'level'=>$level,'group'=>$group];
}
    // 获取分类列表  //index不能传入参数！！！
    public function index() {
        // $tree = categoryTree(1); // 固定 status 为 1
        // return response()->json($tree);
        $data = cache_category_all(); // 如果没有 return，就 $data 是 null
        return response()->json($data);
    }
    public function show($id){
        $category = Category::findOrFail($id);
        return cat_success($category);
    }



     public function store(Request $request) {
        // 验证
        $input=$this->checkInput($request);
        if(!is_array($input)) return $input;
        $pid=$input['pid'];
        $level=$input['level'];
        // 插入数据
        $category = Category::create([
            'name'   => $request->name,
            'pid'    => $pid,
            'level'  => $level,
            'status' => $request->input('status', 1),
        ]);
        clear_cache_category();
        return cat_success($category, '创建成功', 201);
    }


    public function update(Request $request,$id){
        $category=Category::findOrFail($id);
        $input=$this->checkInput($request);
        if(!is_array($input)) return $input;
        if($input['pid']==$id) return cat_error('父分类不能是自己');
        $category->update([
            'name'=>$request->name,
            'pid'=>$input['pid'],
            'level'=>$input['level'],
            'status'=>$request->input('status',1),
        ]);
        clear_cache_category();
        return cat_success($category,'更新成功');
    }
    // 启用与禁用
    public function destroy($id) {
        $category = Category::findOrFail($id);
        //等于1 就返回0，否则：返回1
        $category->status==1?0:1;
        $category->save();
        clear_cache_category();
        return cat_success($category,'更新成功');
    }
}

